<template>
  <div class="table">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 用户列表
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAll">批量删除</el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          class="ml0 mr10"
          @click="handlerAddAll"
        >批量新增</el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          class="ml0 mr10"
          @click="addOneUser"
        >新增</el-button>
        <el-input v-model="select_pattern" placeholder="筛选关键词" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="iuRegistertime" label="注册日期" sortable :formatter="formatter"></el-table-column>
        <el-table-column prop="iuLname" label="登录名" width="120"></el-table-column>
        <el-table-column prop="iuCompany" label="所属机构"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :paginationData="paginationData" v-on:childrenData="childrenData"></Pagination>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="title" :visible.sync="editVisible" width="35%">
      <el-steps :active="dialog.active" simple finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="授予角色"></el-step>

      </el-steps>
      <el-form ref="form" v-show="dialog.active==1" label-position="left" :model="form" label-width="15%">
        <el-form-item label="登录名">
          <el-input v-model="form.iuLname"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.iuPassword"></el-input>
        </el-form-item>
        <el-form-item label="所属机构">
          <el-input v-model="form.iuCompany"></el-input>
        </el-form-item>
      </el-form>
      <el-transfer v-show="dialog.active==2"
          filterable
          
          filter-placeholder="请输入角色名称!"
          v-model="transfer.value"
          :titles="['可选角色', '新用户角色']"
          :data="transfer.data">
        </el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button v-show="dialog.active==2" @click="dialog.active=1">上一步</el-button>
        <el-button v-show="dialog.active==1" @click="dialog.active=2;getCurUserRole()">下一步</el-button>
        <el-button v-show="dialog.active==2" type="primary" @click="saveEdit">保 存</el-button>
        <!-- <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button> -->
      </span>
    </el-dialog>
    <!-- 批量新增 -->
    <el-dialog title="批量新增" :visible.sync="addVisible" width="30%">
      <el-upload
        class="upload-demo"
        multiple
        ref="upload"
        action="/api/sys/user/addBath"
        :on-change="handlerChange"
        :on-success="responseHandler"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="false"
        accept=".xlsx,.xls"
        limit=1
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
        >上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传一个xlsx或xls文件，且不超过10mb</div>
      </el-upload>
    </el-dialog>

    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRow">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import Pagination from '../base/Pagination.vue'
export default {
  components: {
    Pagination
  },
  name: "user-list",
  data() {
    return {
      tableData: [],
      paginationData: {
        total: 0,
        pagesize: 7,
        pagesizes: [7, ],
        currentPage: 1,
        layout: "total, sizes, prev, pager, next, jumper"
      },
      curPage: {
        pagesize: 7,
        currentPage: 1
      },
      dialog:{
        title:'',
        active:1
      },
      transfer:{
        value:[],
        data:[]
      },
      multipleSelection: [],
      select_pattern: "",
      del_list: [],
      is_search: false,
      editVisible: false,
      delVisible: false,
      addVisible: false,
      fileList: [],
      form: {
        iuRegistertime: "",
        iuLname: "",
        iuId: ""
      },
      idx: -1,
      id: -1,
      title: "",
      handlerData: 0
    };
  },
  created() {
    this.getData();
  },
  methods: {
    //文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    //添加文件是处理
    handlerChange(file, fileList){
      debugger;
      if(fileList.length>0){
        this.fileList.filter(function(x){
          return x.name!=file.name
        })
      }
    },
    //文件上传前的校验
    beforeUpload(file){
        let filesuffix = file.name.substring(file.name.lastIndexOf('.')+1)
				let extension = filesuffix === 'xls'
				let extension2 = filesuffix === 'xlsx'
        let isLt2M = file.size / 1024 / 1024 < 10

        if(!extension && !extension2) {
					this.$message({
						message: '上传文件只能是 xls、xlsx格式!',
						type: 'warning'
					});
				}
				if(!isLt2M) {
					this.$message({
						message: '上传文件大小不能超过 10MB!',
						type: 'warning'
					});
				}
				return extension || extension2 && isLt2M

    },
    //批量新增弹框
    handlerAddAll() {
      this.addVisible = true;
    },
    //文件上传成功
    responseHandler(response, file, fileList){
      debugger

      this.fileList=[];
      if(response.status){
        this.$message({
						message: '批量新增用户成功！',
						type: 'success'
        });
        this.addVisible=false;
        this.getData();
      }else{
        if(response.respMsg!=null){
          this.addVisible=false;
          this.$message({
						message: response.data+response.respMsg,
						type: 'error'
				  });
        }else{
          this.addVisible=false;
          this.$message({
						message: '批量新增用户失败！',
						type: 'error'
				  });
        }
      }
    },
    //多选项
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //console.log(val);
    },

    // 获取 用户数据
    getData() {
      let _self = this;
      //如果不是搜索调用设为‘’
      if (!this.is_search) {
        this.select_pattern = "";
      }
      this.$axios
        .get("/api/sys/user/getUserList", {
          params: {
            pageNum: this.curPage.currentPage,
            pageSize: this.curPage.pagesize,
            select_pattern: this.select_pattern
          }
        })
        .then(function(response) {
          //debugger;
          _self.tableData = response.data.list;
          _self.is_search = false;
          _self.paginationData.total = response.data.total;
        });
    },
    //根据条件查询
    search() {
      if (!this.is_search) {
        this.is_search = true;
        this.paginationData.currentPage = 1;
        this.getData();
      }
    },
    //时间格式处理
    formatter(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    delAll() {
      debugger;
      let _curThis = this;
      let length = this.multipleSelection.length;
      if (length > 0) {
        for (let i = 0; i < length; i++) {
          this.del_list.push(this.multipleSelection[i].iuId);
        }
        //console.log(this.del_list.toString());
        this.$axios
          .delete("/api/sys/user/deleteAll", {
            params: { ids: this.del_list.toString() }
          })
          .then(function(response) {
            if (response.data.status) {
              _curThis.$message.success("批量删除成功！");
              _curThis.multipleSelection = [];
              _curThis.del_list = [];
              _curThis.getData();
            } else {
              _curThis.$message.error("批量删除失败！");
            }
          });
      } else {
        this.$message.error("请先选择要删除的用户！");
      }
    },
    handleEdit(index, row) {
      //debugger;
      this.title = "编辑";
      this.handlerData = 1;
      this.idx = index;
      this.id = row.iuId;
      this.form = {
        iuRegistertime: row.iuRegistertime,
        iuLname: row.iuLname,
        iuId: row.iuId,
        iuCompany:row.iuCompany
      };
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      //debugger;
      let _curThis = this;
      if (this.handlerData == 1) {
        if (this.tableData[this.idx].iuId === this.id) {
          this.$axios
            .put("/api/sys/user/putUser", {
              iuRegistertime: this.form.iuRegistertime,
              iuId: this.form.iuId,
              iuLname: this.form.iuLname,
              list:this.transfer.value
            })
            .then(function(response) {
              if (response.data.status === true) {
                //状态处理
                _curThis.editVisible = false;
                _curThis.handlerData = 0;
                //提示处理
                _curThis.$message.success(`修改第 ${_curThis.idx + 1} 行成功`);
                _curThis.$set(_curThis.tableData, _curThis.idx, _curThis.form);
              }
            });
        }
      } else if (this.handlerData == 2) {
        this.$axios
          .get("/api/sys/user/ifPresentLname", {
            params: {
              iuLname: this.form.iuLname
            }
          })
          .then(function(response) {
            if (response.data.status === true) {
              _curThis.$message.error(
                `登录名 ${_curThis.form.iuLname} 已经存在`
              );
            } else {
              _curThis.$axios
                .post("/api/sys/user/addUser", _curThis.form)
                .then(function(response) {
                  if (response.data.status === true) {
                    //状态处理
                    _curThis.editVisible = false;
                    _curThis.handlerData = 0;
                    //_curThis.tableData.push(_curThis.form);
                    _curThis.$message.success(
                      `用户 ${_curThis.form.iuLname} 添加成功`
                    );
                    _curThis.getData();
                  }
                });
            }
          });
      }
    },

    getCurUserRole(){
      let _self = this;
      if(this.transfer.data.length>0){
        return;
      }
      debugger
      this.$axios.get("/api/sys/role/getCurUserRole")
      .then(function(response){
          if(response.data.status === true){
              let tmpdata = response.data.data;
              for(let i=0;i<response.data.data.length;i++){
                _self.transfer.data.push({
                  key:response.data.data[i].iroleid,
                  label:response.data.data[i].irolename,
                  disabled:false
                })
              }
          }
      });
    },
    // 确定删除
    deleteRow() {
      //debugger;
      let _curThis = this;
      if (this.tableData[this.idx].iuId === this.id) {
        this.$axios
          .delete("/api/sys/user/deleteById", {
            params: {
              iuId: this.id
            }
          })
          .then(function(response) {
            if (response.data.status === true) {
              _curThis.delVisible = false;
              //_curThis.tableData.splice(_curThis.idx, 1);
              _curThis.$message.success("删除成功");
              _curThis.getData();
            }
          });
      }
    },
    handleDelete(index, row) {
      debugger
      this.idx = index;
      this.id = row.iuId;
      this.delVisible = true;
    },
    addOneUser() {
      this.editVisible = true;
      this.title = "新增";
      this.form = {};
      this.handlerData = 2;
    },
    childrenData(childrenData) {
      this.curPage = childrenData;
      this.getData();
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.ml0 {
  margin-left: 0px;
}
</style>
